package com.ks.app.admin.action;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.ParentPackage;

@ParentPackage("struts-default")
@InterceptorRef("defaultStack")
public class ShowImageAction extends BaseAction{

	private static final long serialVersionUID = -24915823455849415L;
	private Log log = LogFactory.getLog(this.getClass());
	
	@Action(value="showImage")
	public String showImage(){
			
		String logoImgPath = request.getParameter("imgurl");
		String filestr     = request.getParameter("imgfile");
		BufferedImage bi = null;
		
		try {

			// 从网址取图片
			if (logoImgPath != null) {
				
				String suffix = getSuffix(logoImgPath);

				InputStream in = new URL(logoImgPath).openStream();// new
				// FileInputStream(logoImgPath);
				// 以byte流的方式打开文件
				if(in != null && in.available()<200*1024){
					bi = ImageIO.read(in);
					response.setContentType("image/" + suffix);
					OutputStream outstream = response.getOutputStream();
					ImageIO.write(bi, suffix, outstream);
					outstream.close();
				}else{
					log.info("图片大小大于200K"+logoImgPath);
				}
				
			}

			// 从磁盘中取图片
			if (filestr != null) {
	
					String filePath = filestr;					
					File f = new File(filePath);
					if(f != null && f.length()<200*1024){
						byte[] b = new byte[(int) f.length()];
						FileInputStream fis = new FileInputStream(f);
						fis.read(b);
						String suffix = getSuffix(filePath);
						response.reset();
						response.setContentType("image/" + suffix);
						ServletOutputStream out = response.getOutputStream();
						out.write(b);
						out.close();
					}else{
						log.info("图片大小大于200K："+filePath);
					}
			}

		} catch (IOException e){ // 错误处理
			log.info(e.getMessage());
		}
		
		return null;
	}
	
	
	private String getSuffix(String logoImgPath) {
		if (logoImgPath == null || "".equals(logoImgPath)) {
			System.out.println("图片URL为空，参数错误！");
			return null;
		}
		int i = logoImgPath.lastIndexOf(".");
		String suf = logoImgPath.substring(++i);
		return suf;
	}
}
